package com.gimi.test_jpa.com.gimi.aop;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.gimi.test_jpa.com.gimi.dto.BaseDto;
import com.gimi.test_jpa.com.gimi.entity.login.LoginLog;
import com.gimi.test_jpa.com.gimi.jpa.login.LoginLogJap;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.hibernate.mapping.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Aspect
@Component
@Slf4j
public class MyAspect {
    @Autowired
    private LoginLogJap loginLogJap;

    @Pointcut("execution(* com.gimi..*.*Service.*(..))")
    public void serviceAop() {
    }

    @Pointcut("execution(* com.gimi.test_jpa.com.gimi.controller.login.LoginController.login(..))")
    public void loginLogAop() {
    }

    @Around("serviceAop()")
    public Object serviceAopAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println(">>>>>>>>>>>>>>>>>>>serviceAop执行");
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = signature.getMethod();
        Parameter[] parameters = method.getParameters();
//        log.info("获得参数的类型为：{}，名称为：{}",parameters[0].getType(),parameters[0].getName());
//        log.info("获得方法执行的参数为：{}",proceedingJoinPoint.getArgs());

        //service层参数中含有BaseDto 为该BaseDto注入updateTime
        Object[] args = proceedingJoinPoint.getArgs();
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof BaseDto) {
                BaseDto baseDto = (BaseDto) args[i];
                baseDto.setUpdateTime(new Date());
                args[i] = baseDto;
            }
        }
        Object proceed = proceedingJoinPoint.proceed(args);
        return proceed;
    }

    @AfterReturning(pointcut = "loginLogAop()", returning = "result")
    public void afterReturning(JoinPoint point, Object result) {
        List<Object> args = Arrays.asList(point.getArgs());
//        String methodName = point.getSignature().getName();
//        System.out.println("连接点方法为：" + methodName + ",参数为：" + args + ",目标方法执行结果为：" + result);
        HashMap map = (HashMap) result;
        LoginLog loginLog = new LoginLog();
        loginLog.setLoginTime(new Date());
        loginLog.setUsername((String) args.get(0));
        loginLog.setPassword((String) args.get(1));
        loginLog.setLogMsg(map.get("message").toString());
        loginLogJap.save(loginLog);
        log.info("登录日志记录成功！");
    }
}

